package com.dm.wallpaper.library.database;

import com.dm.wallpaper.library.items.Category;
import com.dm.wallpaper.library.items.Wallpaper;
import com.dm.wallpaper.library.utils.ImageSize;

import java.util.ArrayList;
import java.util.List;

/**
 * 数据库有问题，所以缓存所有的对象
 */
public class DataProvider {

    private static DataProvider instance;

    private List<Wallpaper> wallpaperList = new ArrayList<>();

    private List<Category> categoryList = new ArrayList<>();

    private DataProvider() {

    }

    public static DataProvider getInstance() {
        if (instance == null) {
            instance = new DataProvider();
        }
        return instance;
    }

    public List<Wallpaper> getWallpapers() {
        List<Wallpaper> wallpapers = Database.get().getWallpapers();
        if (wallpapers.size() > 0) {
            wallpaperList.clear();
            wallpaperList.addAll(wallpapers);
        }
        return new ArrayList<>(wallpaperList);
    }

    public List<Wallpaper> getLatestWallpapers() {
//        List<Wallpaper> wallpapers = Database.get(mContext).getLatestWallpapers();
//        if (wallpapers.size() > 0) {
//            latestWallpapers.addAll(wallpapers);
//        }
        List<Wallpaper> latestWallpapers = Database.get().getLatestWallpapers();

//        latestWallpapers.sort((w1, w2) -> {
//            String addedOn = w1.getAddedOn();
//            if (addedOn == null) {
//                addedOn = "";
//            }
//            return addedOn.compareTo(w2.getAddedOn());
//        });

        return latestWallpapers;
    }

    public List<Category> getCategorys() {
        List<Category> categories = Database.get().getCategorys();
        if (categories.size() > 0) {
            categoryList.clear();
            categoryList.addAll(categories);
        }
        return new ArrayList<>(categoryList);
    }

//    public void favoriteWallpaper(int localid, int b) {
//
//        for (int i = 0; i < wallpaperList.size(); i++) {
//            Wallpaper wallpaper = wallpaperList.get(i);
//            if (wallpaper.getLocalid() == localid) {
//                wallpaper.setFavorite(b);
//                break;
//            }
//        }
//        Database.get().favoriteWallpaper(localid, b);
//    }

    public void updateWallpaper(int localIdID, int size, ImageSize dimensions) {
        if (dimensions == null) {
            return;
        }
        for (int i = 0; i < wallpaperList.size(); i++) {
            Wallpaper wallpaper = wallpaperList.get(i);
            if (wallpaper.getId() == localIdID) {
                wallpaper.setDimensions(dimensions);
                wallpaper.setSize(size);
                break;
            }
        }
        Database.get().updateWallpaper(localIdID, size, dimensions);
    }

    public Wallpaper getWallpaperByLocalIdID(int localIdID) {
        return Database.get().getWallpaperByLocalIdID(localIdID);
    }

}
